package sentry

import (
	"context"
	log "gitee.com/xuyiping_admin/pkg/logger/logrus"

	"github.com/getsentry/sentry-go"
)

func MustInit(dsn string, options ...*sentry.ClientOptions) {
	var option *sentry.ClientOptions
	if len(options) != 0 {
		option = options[0]
	} else {
		option = &sentry.ClientOptions{
			Dsn:              dsn,
			AttachStacktrace: true,
			IgnoreErrors:     []string{"400", "401", "404"},
		}
	}

	if err := sentry.Init(*option); err != nil {
		log.Errorf("ExportSentryOption error: %v", err)
		return
	}
}

func ReportPanic(ctx context.Context, rval interface{}) {
	hub := hubFromContext(ctx)
	hub.RecoverWithContext(ctx, rval)
	return
}

func hubFromContext(ctx context.Context) *sentry.Hub {
	hub := sentry.GetHubFromContext(ctx)
	if hub == nil {
		hub = sentry.CurrentHub()
	}
	return hub
}

func AddTag(ctx context.Context, k, v string) {
	hub := sentry.GetHubFromContext(ctx)
	if hub == nil {
		return
	}
	hub.Scope().SetTag(k, v)
}

func AddTags(ctx context.Context, tags map[string]string) {
	hub := sentry.GetHubFromContext(ctx)
	if hub == nil {
		return
	}
	hub.Scope().SetTags(tags)
}

func AddExtra(ctx context.Context, k string, v interface{}) {
	hub := sentry.GetHubFromContext(ctx)
	if hub == nil {
		return
	}
	hub.Scope().SetExtra(k, v)
}

func AddExtras(ctx context.Context, extra map[string]interface{}) {
	hub := sentry.GetHubFromContext(ctx)
	if hub == nil {
		return
	}
	hub.Scope().SetExtras(extra)
}
